﻿<html>
<head>
<script src="jquery-1.4.2.min.js"></script>
<script>
var sendRealTime = false;
var jsonobj;
var jsonRealTime;
var failRefreshTime = 10*1000;
var timeoutCode;
var timeSpan = parseInt(localStorage.getItem('timeSpan') || "20");
var dayCount = parseInt(localStorage["dayCount"] || "5");
var dsCodeMode = (localStorage['dsCodeMode'] == "1");

var canvas;
var canvasContext;
var browserImg;

function init() {
  canvas = document.getElementById('canvas');
  canvasContext = canvas.getContext('2d');
  loadDsCodeMode(dsCodeMode);
  loadSetting();
}

function loadSetting() {
    failRefreshTime = 10 * 1000;
    timeSpan = parseInt(localStorage.getItem('timeSpan') || "20");
    dayCount = parseInt(localStorage["dayCount"] || "5");
    dsCodeMode = (localStorage['dsCodeMode'] == "1");

    if (dayCount < 5) {
        $('[_day=5]').hide();
    }
    else {
        $('[_day=5]').show();
    }
    if (dayCount < 4) {
        $('[_day=4]').hide();
    }
    else {
        $('[_day=4]').show();
    }
    if (dayCount < 3) {
        $('[_day=3]').hide();
    }
    else {
        $('[_day=3]').show();
    }
    if (dayCount < 2) {
        $('[_day=2]').hide();
    }
    else {
        $('[_day=2]').show();
    }
}

function loadDsCodeMode(isDsCodeMode){
	dsCodeMode = isDsCodeMode;
	if (isDsCodeMode){
		timeSpan = 20;
	   document.getElementById('linkLunar').innerText = '';
	} else {
	   document.getElementById('linkLunar').innerText = '︾万年历';
	}
	document.getElementById('aRefresh').innerText = getText("refresh");
	document.getElementById('aSetting').innerText = getText("setting");
}

function getText(key){
	if (!dsCodeMode){
		switch (key){
			case "day1":
			return "今天";
			case "day2":
			return "明天";
			case "day3":
			return "后天";
			
			case "refresh":
			return "刷新";
			case "setting":
			return "定制";
			case "details":
			return "详细预报";
			
			case "update time:":
			return "";
		}
	}
	return key;
}
// 加载天气
function loadWeather(){
	if (timeoutCode){
		clearTimeout(timeoutCode);
	}
	chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
	chrome.browserAction.setBadgeText({text:'..'});
	var rs= "http://61.4.185.48:81/g/";
//	var cookieinfo1= getCookie('newcity1');
//	var id1;
	
	var cityList = localStorage["cityList"];
	
	var url1= '';
	var start1=url1.indexOf("=");
	var end1=url1.indexOf("T");
	// 直接获取某指定城市
	if(start1!=-1) {
		// 目前不会到这里来
		console.log("if(start1!=-1) { id:");
	}
	// 根据cookie获取城市
	else {
		document.getElementById('weatherList').innerHTML = '';
		if((!cityList) || dsCodeMode) {
			var js = document.createElement("script"); 
			js.setAttribute("type", "text/javascript");
			js.setAttribute("src",rs);
			document.body.insertBefore(js, null);
		} else {
		    var arrs = cityList.split(/\,/g);
//			id1=cookieinfo1;
//			console.log("id1=cookieinfo1; id:"+id1);

		    var isSuccess;
		    for (var i = 0; i < arrs.length; i++) {
		        document.getElementById('weatherList').appendChild(document.createElement("hr"));
		        isSuccess = returndata(arrs[i], i == 0);
		        if (!isSuccess) {
		            break;
		        }
		    }

		    // 成功
		    if (isSuccess) {
		        // 定时刷新
		        timeoutCode = setTimeout('loadWeather()', timeSpan * 1000 * 60);
		        failRefreshTime = 10 * 1000;
		    }
		    // 失败
		    else {
		        chrome.browserAction.setBadgeBackgroundColor({ color: [190, 190, 190, 230] });
		        chrome.browserAction.setBadgeText({ text: '?' });
		        timeoutCode = setTimeout('loadWeather()', failRefreshTime);
		        failRefreshTime = failRefreshTime * 2;
		    }
		}
	}
}
// 获取城市的js的回调方法
function id_callback(){
	std = id;
	if(typeof(id)=="undefined"){
		chrome.browserAction.setBadgeBackgroundColor({color:[190, 190, 190, 230]});
		chrome.browserAction.setBadgeText({text:'??'});
		console.error('获取城市失败');
	} else {
		//id1=std;
		time=new Date();
		time.setTime(time.getTime()+365*24*60*60*1000*10);
		date=time.toGMTString();
		document.cookie = 'newcity1=' + escape(std)+ ';expires='+date;
		returndata(std,true);
	}
}
// 获取天气数据，参数id为城市id
function returndata(id,isFirst){
   var tableCityWeather = document.getElementById("cityWeatherSample").cloneNode(true);
   document.getElementById('weatherList').appendChild(tableCityWeather);

   tableCityWeather.getElementsByClassName("t1")[0].href = "http://www.weather.com.cn/html/weather/" + id + ".shtml";
   tableCityWeather.getElementsByClassName("t1total")[0].href = "http://www.weather.com.cn/html/weather/" + id + ".shtml";

	var datastr1='http://m.weather.com.cn/data/'+id+'.html';
	var realTimeDatastr1 = 'http://www.weather.com.cn/data/sk/'+id+'.html';
	sendRealTime = false;
	var isSuccess = false;
	if (PostOrder(datastr1)){
		HandleStateChange();
		sendRealTime = true;
		if (PostOrder(realTimeDatastr1)){
			HandleStateChange();
			
			isSuccess = true;
			
			var cityname=jsonobj.weatherinfo.city;
			var temp1=jsonobj.weatherinfo.temp1;
			var temp2=jsonobj.weatherinfo.temp2;
			var img1=jsonobj.weatherinfo.img1;
			var img2=jsonobj.weatherinfo.img2;
			var img3=jsonobj.weatherinfo.img3;
			var img4=jsonobj.weatherinfo.img4;
			var zs=jsonobj.weatherinfo.index_d;
			var uv=jsonobj.weatherinfo.index_uv;
			var zs48=jsonobj.weatherinfo.index48_d;
			var uv48=jsonobj.weatherinfo.index48_uv;
			var zssm="中国天气网今日天气指数 紫外线指数:"+uv+"。"+"穿衣指数:"+zs;
			var zssm48="中国天气网明日天气指数 紫外线指数:"+uv48+"。"+"穿衣指数:"+zs48;
			var weather1=jsonobj.weatherinfo.weather1;
			var weather2=jsonobj.weatherinfo.weather2;
			var date_y = jsonobj.weatherinfo.date_y;

			var dateToday = new Date(parseInt(date_y.substr(0, 4)), parseInt(date_y.substr(5)) - 1, parseInt(date_y.substr(date_y.indexOf("月") + 1)));

			for (var i = 1; i < 6; i++) {
			    $('#day'+i).empty();
			    $('<b/>').html(getWeek(dateToday)).appendTo($('#day' + i));
			    $('<span/>').html('(' + dateToday.getDate() + '日)').appendTo($('#day' + i));
			    if (dateToday.getDay() == 0 || dateToday.getDay() == 6) {
			        $('#day' + i).css('color', 'rgb(198,11,2)');
			    } else {
			        $('#day' + i).css('color', '#000000');
			    }
			    
			    dateToday.setDate(dateToday.getDate() + 1);
			}
			
			var date_w=jsonobj.weatherinfo.week;
			var date=date_y+date_w;	

			if(img2=="99") {
				img2=img1;
			} else if(img4="99") {
				img4=img3;
			}
			
			if (dsCodeMode){
				tableCityWeather.getElementsByClassName("city1")[0].innerHTML ='';
			} else {
				tableCityWeather.getElementsByClassName("city1")[0].innerHTML =cityname;
			}
			tableCityWeather.getElementsByClassName("small1")[0].src="http://m.weather.com.cn/weather_img/"+img1+".gif"
			//tableCityWeather.getElementsByClassName("small2").src="http://m.weather.com.cn/new/n"+img2+".gif"
			tableCityWeather.getElementsByClassName("small3")[0].src="http://m.weather.com.cn/weather_img/"+img3+".gif"
			
			//tableCityWeather.getElementsByClassName("small4").src="http://m.weather.com.cn/new/n"+img4+".gif"
			
			// 第3天
			tableCityWeather.getElementsByClassName("small5")[0].src = "http://m.weather.com.cn/weather_img/" + jsonobj.weatherinfo.img5 + ".gif"

			// 第4天
			tableCityWeather.getElementsByClassName("small7")[0].src = "http://m.weather.com.cn/weather_img/" + jsonobj.weatherinfo.img7 + ".gif"
			
			// 第5天
			tableCityWeather.getElementsByClassName("small9")[0].src = "http://m.weather.com.cn/weather_img/" + jsonobj.weatherinfo.img9 + ".gif"
			
			if (dsCodeMode){
			   tableCityWeather.getElementsByClassName('atC')[0].innerText = jsonRealTime.weatherinfo.temp;
			   tableCityWeather.getElementsByClassName('atSD')[0].innerText = jsonRealTime.weatherinfo.SD;
			   
				tableCityWeather.getElementsByClassName("small1")[0].title='';
				tableCityWeather.getElementsByClassName("small3")[0].title='';
			
				tableCityWeather.getElementsByClassName("temp1")[0].innerHTML =processC(temp1);
				tableCityWeather.getElementsByClassName("temp2")[0].innerHTML =processC(temp2);
				tableCityWeather.getElementsByClassName("temp3")[0].innerHTML = processC(jsonobj.weatherinfo.temp3);
				tableCityWeather.getElementsByClassName("temp4")[0].innerHTML = processC(jsonobj.weatherinfo.temp4);
				tableCityWeather.getElementsByClassName("temp5")[0].innerHTML = processC(jsonobj.weatherinfo.temp5);

				tableCityWeather.getElementsByClassName("weather3")[0].innerHTML = '';
				tableCityWeather.getElementsByClassName("weather4")[0].innerHTML = ''
				tableCityWeather.getElementsByClassName("weather5")[0].innerHTML = ''; ;
				tableCityWeather.getElementsByClassName("weather1")[0].innerHTML ='';
				tableCityWeather.getElementsByClassName("weather2")[0].innerHTML ='';
			} else {
			   tableCityWeather.getElementsByClassName('atC')[0].innerText = jsonRealTime.weatherinfo.temp+'℃';
			   tableCityWeather.getElementsByClassName('atSD')[0].innerText = jsonRealTime.weatherinfo.SD;
			   
				tableCityWeather.getElementsByClassName("small1")[0].title=zssm;
				tableCityWeather.getElementsByClassName("small3")[0].title=zssm48;
			
				tableCityWeather.getElementsByClassName("temp1")[0].innerHTML =temp1;
				tableCityWeather.getElementsByClassName("temp2")[0].innerHTML =temp2;
				tableCityWeather.getElementsByClassName("temp3")[0].innerHTML = jsonobj.weatherinfo.temp3;
				tableCityWeather.getElementsByClassName("temp4")[0].innerHTML = jsonobj.weatherinfo.temp4;
				tableCityWeather.getElementsByClassName("temp5")[0].innerHTML = jsonobj.weatherinfo.temp5;

				tableCityWeather.getElementsByClassName("weather3")[0].innerHTML = jsonobj.weatherinfo.weather3;
				tableCityWeather.getElementsByClassName("weather4")[0].innerHTML = jsonobj.weatherinfo.weather4;
				tableCityWeather.getElementsByClassName("weather5")[0].innerHTML = jsonobj.weatherinfo.weather5;
				tableCityWeather.getElementsByClassName("weather1")[0].innerHTML =weather1;
				tableCityWeather.getElementsByClassName("weather2")[0].innerHTML =weather2;
				
				tableCityWeather.getElementsByClassName("wind1")[0].title = tableCityWeather.getElementsByClassName("wind1")[0].innerHTML = jsonobj.weatherinfo.wind1;
				tableCityWeather.getElementsByClassName("wind2")[0].title = tableCityWeather.getElementsByClassName("wind2")[0].innerHTML = jsonobj.weatherinfo.wind2;
				tableCityWeather.getElementsByClassName("wind3")[0].title = tableCityWeather.getElementsByClassName("wind3")[0].innerHTML = jsonobj.weatherinfo.wind3;
				tableCityWeather.getElementsByClassName("wind4")[0].title = tableCityWeather.getElementsByClassName("wind4")[0].innerHTML = jsonobj.weatherinfo.wind4;
				tableCityWeather.getElementsByClassName("wind5")[0].title = tableCityWeather.getElementsByClassName("wind5")[0].innerHTML = jsonobj.weatherinfo.wind5;
			}
			
			// 显示日期
//			if (dsCodeMode){
//				document.getElementById("todayNum").innerHTML = '';
//			} else {
//				document.getElementById("todayNum").innerHTML = date_y;
//			}
			
			// 改变浏览器按钮的显示
			if (isFirst){
			   document.getElementById("browserImg").onload = drawIcon;
			   // 根据设置判断是显示今天还是明天的天气图标
			   var dateSelect = localStorage.getItem('dateSelect');
			   if (dateSelect&&dateSelect =='tomorrow'){
				   document.getElementById("browserImg").src="http://m.weather.com.cn/weather_img/"+img3+".gif"
			   } else {
				   document.getElementById("browserImg").src="http://m.weather.com.cn/weather_img/"+img1+".gif"
			   }
			   var timeString = new Date().getHours()+":"+new Date().getMinutes()+":"+new Date().getSeconds();
			   document.getElementById('updateTime').innerText = getText('update time:')+timeString;
			
			   // 显示文字
			   var strTip;
			   if (dsCodeMode){
				   strTip = 'now air temperature:'+jsonRealTime.weatherinfo.temp +
					   'C\r\nday1:'+processC(temp1)+'\r\nday2:'+processC(temp2)+'\r\nday3:'+processC(jsonobj.weatherinfo.temp3)
					   +'\r\nupdate time:'+timeString;
			   } else {
				   strTip = cityname+'现在气温：'+jsonRealTime.weatherinfo.temp +
					   '℃\r\n今天：'+weather1+temp1+'\r\n明天：'+weather2+temp2+'\r\n后天：'+jsonobj.weatherinfo.weather3+jsonobj.weatherinfo.temp3
					   +'\r\n上次刷新时间：'+timeString;
			   }
			   chrome.browserAction.setTitle({title:strTip});
			   chrome.browserAction.setBadgeBackgroundColor({color:[0, 97, 255,100]});
			   //chrome.browserAction.setBadgeBackgroundColor({color:[0, 0, 0, 255]});
			   chrome.browserAction.setBadgeText({text:Math.round(jsonRealTime.weatherinfo.temp).toString()});
			}
		}
	}

    return isSuccess;
}
function getWeek(date) {
    switch (date.getDay()) {
        case 0:
            return '周日';
        case 1:
            return '周一';
        case 2:
            return '周二';
        case 3:
            return '周三';
        case 4:
            return '周四';
        case 5:
            return '周五';
        case 6:
            return '周六';
    }
}
function processC(inputC){
	var index = inputC.indexOf('~');
	return parseInt(inputC.substr(0,index-1))+"C~"+parseInt(inputC.substr(index+1))+"C";
}

var xmlhttp=null; 
// 同步处理
function HandleStateChange() 
{
	if (xmlhttp.readyState == 4){
		var jsontext =xmlhttp.responseText;
		var func = new Function("return " + jsontext);
		if (!sendRealTime){
			jsonobj = func();
		} else {
			jsonRealTime = func();
		}
	}
}
// 同步ajax获取天气
function PostOrder(xmldoc) 
{ 
	xmlhttp = new XMLHttpRequest();
	xmlhttp.open("GET", xmldoc,false); 
	xmlhttp.onreadystatechange= HandleStateChange;
	try {
		xmlhttp.send(null); 
	}catch(e){
		return false;
		console.error(e);
	}
	return true;
}
function setCookie(name, value) 
{ 
    var argv = setCookie.arguments; 
    var argc = setCookie.arguments.length; 
    var expires = (argc > 2) ? argv[2] : null; 
    if(expires!=null) 
	{ 
        var LargeExpDate = new Date (); 
         LargeExpDate.setTime(LargeExpDate.getTime() + (expires*1000*3600*24));         
     	} 
     document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString())); 
}
function getCookie(Name) 
{ 
    var search = Name + "=" 
    if(document.cookie.length > 0) 
    	{ 
         offset = document.cookie.indexOf(search) 
        if(offset != -1) 
        	{ 
             offset += search.length 
             end = document.cookie.indexOf(";", offset) 
            if(end == -1) end = document.cookie.length 
            return unescape(document.cookie.substring(offset, end)) 
         } 
        else return "" 
     } 
} 
function deleteCookie(name) 
{ 
	 var expdate = new Date(); 
	  expdate.setTime(expdate.getTime() - (86400 * 1000 * 1)); 
     setCookie(name, "", expdate); 
} 
function getInnerHTML(){
	return document.getElementById('mainDiv').innerHTML;
}

function drawIcon() {
	browserImg = document.getElementById('browserImg');
	canvasContext.save();
	canvasContext.drawImage(browserImg,0,0,canvas.width,canvas.height);
	canvasContext.restore();
	//canvasContext.stroke();

	chrome.browserAction.setIcon({imageData:canvasContext.getImageData(0, 0, canvas.width,canvas.height)});
}
function checkAndWelcome(notExistsShow) {
    var currentVersion = '2.1.0';
    if (notExistsShow) {
        if (!localStorage['CurrentVersion']) {
            localStorage['CurrentVersion'] = currentVersion;
            chrome.tabs.create({ url: chrome.extension.getURL('welcome.htm'), selected: true });
        }
    }
    else {
        if (localStorage['CurrentVersion'] != currentVersion) {
            localStorage['CurrentVersion'] = currentVersion;
            chrome.tabs.create({ url: chrome.extension.getURL('updateWelcome.htm') });
        }
    }
}
// 显示欢迎页
checkAndWelcome(true);
</script>
</head> 
<body onload="init();loadWeather();">
<img id="browserImg" style="width:19px;height:19px;">
<canvas id="canvas" width="19" height="19">
<div id="mainDiv">
<p style="margin:5px;text-align:right;">
<span class="part"><a id="linkLunar" target="_blank" href="wannianli.htm" onclick="return toggleLunar();">︾万年历</a></span>
<span class="part"><a href="options.html" id="aSetting" target="_blank">定制</a></span>
<span class="part"><a href='#' onclick='chrome.extension.getBackgroundPage().loadWeather();
loadHtml();return false;' id="aRefresh">刷新</a><span style="color:#CCCCCC" id="updateTime"></span></span>
</p>
<table>
  <tr> 
    <td style="width:125px;text-align:center;"></td> 
    <td id="day1" _day="1" width="130px"><strong>今&nbsp;&nbsp;天</strong></td>
    <td id="day2" _day="2" width="130px"><strong>明&nbsp;&nbsp;天</strong></td>
    <td id="day3" _day="3" width="130px"><strong>后&nbsp;&nbsp;天</strong></td>
    <td id="day4" _day="4" width="130px"><strong>第四天</strong></td>
    <td id="day5" _day="5" width="130px"><strong>第五天</strong></td>
  </tr>
</table>
<div id="weatherList"></div>
</div>
<table class="s360" id="cityWeatherSample">
  <tr>
    <td scope="row" style="width:130px;text-align:center;"><a class="t1" href="#" target="_blank"><em class="city1"></em></a><a class="t1total" href="#" target="_blank">详情</a></td> 
    <td _day="1" rowspan="2" width="46px"><img class="small1" src="#" alt="" width="50" height="50"></img></td>
    <td _day="1" width="84px"><em class="temp1"></em></td>
    <td _day="2" rowspan="2" width="46px"><img class="small3" src="#" alt="" width="50" height="50"></img></td>
    <td _day="2" width="84px"><em class="temp2"></em></td>
    <td _day="3" rowspan="2" width="46px"><img class="small5" src="#" alt="" width="50" height="50"></img></td>
    <td _day="3" width="84px"><em class="temp3"></em></td>
    <td _day="4" rowspan="2" width="46px"><img class="small7" src="#" alt="" width="50" height="50"></img></td>
    <td _day="4" width="84px"><em class="temp4"></em></td>
    <td _day="5" rowspan="2" width="46px"><img class="small9" src="#" alt="" width="50" height="50"></img></td>
    <td _day="5" width="84px"><em class="temp5"></em></td>
  </tr>
  <tr>
    <td style="width:130px;text-align:center;"><span class="spanAt">实时气温:</span><span class="atC"></span></td> 
    <td _day="1"><em class="weather1"></em></td>
    <td _day="2"><em class="weather2"></em></td>
    <td _day="3"><em class="weather3"></em></td>
    <td _day="4"><em class="weather4"></em></td>
    <td _day="5"><em class="weather5"></em></td>
  </tr>
  <tr>
    <td style="width:130px;text-align:center;"><span class="spanAt">湿度:</span><span class="atSD"></span></td> 
    <td _day="1" colspan="2" style="text-align:center"><div class="wind1"></div></td>
    <td _day="2" colspan="2" style="text-align:center"><div class="wind2"></div></td>
    <td _day="3" colspan="2" style="text-align:center"><div class="wind3"></div></td>
    <td _day="4" colspan="2" style="text-align:center"><div class="wind4"></div></td>
    <td _day="5" colspan="2" style="text-align:center"><div class="wind5"></div></td>
  </tr>
</table>
<script src='http://www.google-analytics.com/ga.js' type='text/javascript'></script>
<script type="text/javascript">
  try{
  var pageTracker = _gat._getTracker("UA-30677288-1");
  pageTracker._trackPageview();
  } catch(err) {}
</script>
</body>
</html>